package br.edu.faculdadeprojecao.si.sisecon.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

@MappedSuperclass
public abstract class AbstractModel<E extends AbstractModel<E>> implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id", updatable = false, nullable = false)
	private Long id = null;

	@Version
	@Column(name = "version")
	private int version = 0;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "lastUpdate")
	private Date lastUpdate;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "createdOn", updatable = false, nullable = false)
	private Date createdOn;

	@PrePersist
	void prePersist() {
		createdOn = new Date();
	}

	@PreUpdate
	void preUpdate() {
		lastUpdate = new Date();
	}

	protected static boolean getBooleanValue(final Boolean value) {
		return Boolean.valueOf(String.valueOf(value));
	}

	public Long getId() {
		return id;
	}

	public boolean isPersisted() {
		return getId() != null;
	}

	@SuppressWarnings("unchecked")
	public E setId(final Long id) {
		if (this.id != null) {
			throw new IllegalStateException("Cannot alter immutable ID of persistent object with id: " + id);
		}
		this.id = id;
		return (E) this;
	}

	public int getVersion() {
		return version;
	}

	@SuppressWarnings("unused")
	private void setVersion(final int version) {
		this.version = version;
	}

	public Date getLastUpdate() {
		return lastUpdate;
	}

	@SuppressWarnings("unchecked")
	public E setLastUpdate(final Date lastUpdate) {
		this.lastUpdate = lastUpdate;
		return (E) this;
	}

	public Date getCreatedOn() {
		return createdOn;
	}

	@SuppressWarnings("unchecked")
	public E setCreatedOn(final Date createdOn) {
		this.createdOn = createdOn;
		return (E) this;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	@SuppressWarnings("rawtypes")
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!getClass().isAssignableFrom(obj.getClass())) {
			return false;
		}
		AbstractModel other = (AbstractModel) obj;
		if (id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!id.equals(other.id)) {
			return false;
		}
		return true;
	}

}
